import os, os.path

import cherrypy
import sys
import json

class CORS:
    headers = [
                ('Content-Type', 'text/plain; charset=utf-8'),
                ('Access-Control-Allow-Origin', '*'),
                ('Access-Control-Allow-Methods', 'GET,POST,OPTIONS,PUT,DELETE'),
                ('Allow', 'GET,POST,OPTIONS,PUT,DELETE'),
                ('Access-Control-Allow-Credentials', 'false'),
                ('Access-Control-Allow-Headers', 'Origin,X-Requested-With,x-token,channel,Content-Type,Accept')
            ]

    normal =  {
            'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
            'tools.response_headers.on': True,
            'tools.response_headers.headers': headers
    }

class WebAck:
    @staticmethod
    def Reply(ok, msg, data=None):
        ack = {
            "code": 200,
            "message": msg,
            "data": {}
        }
        if not ok:
            ack['code'] = 400

        if not data is None:
            ack['data'] = data

        return json.dumps(ack)

class WebPage(object):
    @cherrypy.expose
    def index(self):
        return '<h1>Hello, Wolrd!</h>'

@cherrypy.expose
class FetchService(object):

    def OPTIONS(self):
        pass

    def POST(self):
        cherrypy.session['mystring'] = 'fetch'
        return WebAck.Reply(True, 'fetch')

@cherrypy.expose
class StoreService(object):

    def OPTIONS(self):
        pass

    def POST(self):
        cherrypy.session['mystring'] = 'store'
        return WebAck.Reply(True, 'store')

if __name__ == '__main__':
    conf = {
        '/': {
            'tools.sessions.on': True,
            'tools.staticdir.root': os.path.abspath(os.getcwd()),
        },
        '/store': CORS.normal,
        '/fetch': CORS.normal
    }
    webapp = WebPage()
    webapp.store = StoreService()
    webapp.fetch = FetchService()
    cherrypy.config.update({'server.socket_host': '0.0.0.0',
                            'server.socket_port': 19001})
    cherrypy.quickstart(webapp, '/machine', conf)
